/*
题目链接:https://leetcode.cn/problems/maximum-number-of-tasks-you-can-assign/description/?envType=daily-question&envId=2025-05-01
*/
//题解代码:
class Solution {
public:
    int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {
        sort(tasks.begin(),tasks.end());
        sort(workers.begin(),workers.end());
        int n = tasks.size(), m = workers.size();

        auto check = [&](int mid)->bool{
            int cnt = 0;//使用的药丸数
            deque<int> dq;
            for(int i=0,j=m-1-mid;j<m;++j){
                while(i<=mid && workers[j]+strength>=tasks[i]){
                    dq.push_back(tasks[i++]);
                }
                if(dq.empty()) return false;
                if(workers[j] >= dq.front()){
                    dq.pop_front();
                    continue;
                }else{
                    ++cnt;
                    dq.pop_back();
                }
                if(cnt > pills) return false;
            }
            return true;
        };  

        int l = 0,r = min(n-1,m-1);
        while(l<=r){
            int mid = (l+r)/2;
            if(check(mid)) l = mid + 1;
            else r = mid -1;
        }
        return r+1;
    }
};
